<template>
  <div class="building-monitor">
    <!-- 楼栋监视 -->
    <div class="monitor-section">
      <div class="section-title">楼栋监视</div>
      <div class="building-flow">
        <div
          class="building-card"
          v-for="building in buildingCards"
          :key="building.lcCode"
        >
          <!-- 楼栋基本信息 -->
          <div class="building-header" @click="handleBuildingClick(building)">
            <div class="status-indicator" :style="{ backgroundColor: getStatusColor(building) }"></div>
            <div class="building-info">
              <div class="building-name">{{ building.levelName || building.lcName }}</div>
            </div>
            <div class="building-status" :style="{ color: getStatusColor(building) }">
              {{ getStatusText(building) }}
            </div>
            <div class="building-unit-count">
              {{ getUnitsByBuilding(building.lcCode).length }}个单元
            </div>
          </div>

          <!-- 单元列表 -->
          <div class="unit-list">
            <div
              class="unit-item"
              v-for="unit in getUnitsByBuilding(building.lcCode)"
              :key="unit.lcCode"
            >
              <!-- 单元基本信息 -->
              <div class="unit-header" @click="handleUnitClick(unit)">
                <div class="status-indicator" :style="{ backgroundColor: getUnitStatusColor(unit) }"></div>
                <div class="unit-name">{{ unit.levelName || unit.lcName }}</div>
                <div class="unit-status" :style="{ color: getUnitStatusColor(unit) }">
                  {{ getUnitStatusText(unit) }}
                </div>
                <div class="unit-elevator-count">
                  {{ getElevatorsByUnit(unit.lcCode).length }}部电梯
                </div>
              </div>

              <!-- 电梯列表 -->
              <div class="elevator-list">
                <div
                  class="elevator-item"
                  v-for="elevator in getElevatorsByUnit(unit.lcCode)"
                  :key="elevator.lcCode"
                  @click="handleElevatorClick(elevator)"
                  :class="{
                    'has-alarm': getAlarmCount(elevator) > 0
                  }"
                >
                  <div class="elevator-content">
                    <!-- 左侧：电梯基本信息 -->
                    <div class="elevator-basic">
                      <div class="elevator-name">{{ elevator.levelName || elevator.lcName }}</div>
                      <div class="elevator-info">
                        <span class="info-item">
                          <label>设备:</label>
                          <span>{{ elevator.deviceNo || '--' }}-{{ elevator.channelNo || '--' }}</span>
                        </span>
                        <span class="info-item">
                          <label>米标:</label>
                          <span>{{ elevator.startMeter || '--' }}-{{ elevator.endMeter || '--' }}</span>
                        </span>
                      </div>
                    </div>

                    <!-- 右侧：温度信息 -->
                    <div class="elevator-temp">
                      <div class="current-temp">
                        <label>当前:</label>
                        <span class="temp-value" :style="{ color: getTempColor(getCurrentTemp(elevator)) }">
                          {{ getCurrentTemp(elevator) }}°C
                        </span>
                      </div>
                      <div class="temp-range">
                        <span class="min-temp">{{ getMinTemp(elevator) }}°C</span>
                        <span class="range-separator">~</span>
                        <span class="max-temp">{{ getMaxTemp(elevator) }}°C</span>
                      </div>
                    </div>

                    <!-- 状态指示 -->
                    <div class="elevator-status" :style="{ color: getStatusColor(elevator) }">
                      {{ getStatusText(elevator) }}
                    </div>

                    <!-- 告警徽章 - 添加悬停和点击效果 -->
                    <div
                      v-if="getAlarmCount(elevator) > 0"
                      class="alarm-badge"
                      @click.stop="openAlarmEventsPage(elevator)"
                      :class="{ 'alarm-badge-hoverable': getAlarmCount(elevator) > 0 }"
                      :title="`点击查看${elevator.levelName || elevator.lcName}的告警事件`"
                    >
                      {{ getAlarmCount(elevator) }}
                    </div>
                  </div>

                  <!-- 异常楼层和预警楼层信息 -->
                  <div v-if="getAbnormalFloors(elevator).length > 0 || getWarningFloors(elevator).length > 0"
                       class="floor-info-container">

                    <!-- 只有告警楼层 -->
                    <div v-if="getAbnormalFloors(elevator).length > 0 && getWarningFloors(elevator).length === 0"
                         class="abnormal-floors single-mode"
                         @click.stop="openAlarmEventsPage(elevator)"
                         :class="{ 'clickable-floor-area': getAbnormalFloors(elevator).length > 0 }">
                      <span class="abnormal-label">报警楼层:</span>
                      <span class="floor-list">{{ getAbnormalFloors(elevator).join('、') }}</span>
                    </div>

                    <!-- 只有预警楼层 -->
                    <div v-else-if="getAbnormalFloors(elevator).length === 0 && getWarningFloors(elevator).length > 0"
                         class="warning-floors single-mode">
                      <span class="warning-label">预警楼层:</span>
                      <span class="floor-list">{{ getWarningFloors(elevator).join('、') }}</span>
                    </div>

                    <!-- 既有告警又有预警楼层 -->
                    <div v-else class="dual-floors">
                      <div class="floor-column abnormal-column"
                           @click.stop="openAlarmEventsPage(elevator)"
                           :class="{ 'clickable-floor-area': getAbnormalFloors(elevator).length > 0 }">
                        <span class="abnormal-label">报警:</span>
                        <span class="floor-list">{{ getAbnormalFloors(elevator).join('、') }}</span>
                      </div>
                      <div class="floor-column warning-column">
                        <span class="warning-label">预警:</span>
                        <span class="floor-list">{{ getWarningFloors(elevator).join('、') }}</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getMonitorCards } from '@/api/project/building';

export default {
  name: 'BuildingMonitor',
  props: {
    // 可以接收外部传入的数据，如果不传入则组件内部自行获取
    buildingData: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      buildingCards: [],
      unitCards: [],
      elevatorCards: [],
      loading: false
    };
  },
  mounted() {
    if (this.buildingData) {
      this.setMonitorData(this.buildingData);
    } else {
      this.loadMonitorData();
    }
  },
  methods: {
    // 获取预警楼层
    getWarningFloors(elevator) {
      return elevator.monitorStatus?.warningFloors || [];
    },

    // 设置监视数据（如果从外部传入）
    setMonitorData(data) {
      this.buildingCards = data.buildings || [];
      this.unitCards = data.units || [];
      this.elevatorCards = data.elevators || [];
    },

    // 加载监视数据
    async loadMonitorData() {
      this.loading = true;
      try {
        const response = await getMonitorCards();
        if (response.code === 200) {
          this.buildingCards = response.data.buildings || [];
          this.unitCards = response.data.units || [];
          this.elevatorCards = response.data.elevators || [];
          this.$emit('data-loaded', response.data);
        } else {
          this.$message.error('加载监视数据失败');
          this.$emit('load-error', response);
        }
      } catch (error) {
        console.error('加载监视数据失败:', error);
        this.$message.error('加载监视数据失败');
        this.$emit('load-error', error);
      } finally {
        this.loading = false;
      }
    },

    // 根据楼栋获取单元
    getUnitsByBuilding(buildingCode) {
      return this.unitCards.filter(unit =>
        unit.parentCode === buildingCode || this.extractParentCode(unit.lcCode, 3) === buildingCode
      );
    },

    // 根据单元获取电梯
    getElevatorsByUnit(unitCode) {
      return this.elevatorCards.filter(elevator =>
        elevator.parentCode === unitCode || this.extractParentCode(elevator.lcCode, 4) === unitCode
      );
    },

    // 提取父级编码
    extractParentCode(lcCode, targetLevel) {
      if (!lcCode) return null;

      const parts = lcCode.split('-');
      if (parts.length <= targetLevel) return null;

      let parentCode = '';
      for (let i = 0; i < targetLevel; i++) {
        if (i > 0) parentCode += '-';
        parentCode += parts[i];
      }

      return parentCode;
    },

    // 获取单元状态颜色（基于下属电梯的状态）
    getUnitStatusColor(unit) {
      const elevators = this.getElevatorsByUnit(unit.lcCode);
      if (elevators.length === 0) return '#d9d9d9';

      // 如果任一电梯报警，单元显示报警
      const hasAlarm = elevators.some(elevator =>
        elevator.monitorStatus?.status === 2 || this.getAlarmCount(elevator) > 0
      );
      if (hasAlarm) return '#f5222d';

      // 如果任一电梯预警，单元显示预警
      const hasWarning = elevators.some(elevator =>
        elevator.monitorStatus?.status === 1
      );
      if (hasWarning) return '#faad14';

      return '#52c41a';
    },

    // 获取单元状态文本
    getUnitStatusText(unit) {
      const elevators = this.getElevatorsByUnit(unit.lcCode);
      if (elevators.length === 0) return '未知';

      const hasAlarm = elevators.some(elevator =>
        elevator.monitorStatus?.status === 2 || this.getAlarmCount(elevator) > 0
      );
      if (hasAlarm) return '报警';

      const hasWarning = elevators.some(elevator =>
        elevator.monitorStatus?.status === 1
      );
      if (hasWarning) return '预警';

      return '正常';
    },

    // 获取状态颜色（单个设备）
    getStatusColor(card) {
      const status = card.monitorStatus?.status;
      switch (status) {
        case 0: return '#52c41a'; // 正常 - 绿色
        case 1: return '#faad14'; // 预警 - 橙色
        case 2: return '#f5222d'; // 报警 - 红色
        default: return '#d9d9d9'; // 未知 - 灰色
      }
    },

    // 获取状态文本（单个设备）
    getStatusText(card) {
      const status = card.monitorStatus?.status;
      switch (status) {
        case 0: return '正常';
        case 1: return '预警';
        case 2: return '报警';
        default: return '未知';
      }
    },

    // 获取当前温度
    getCurrentTemp(elevator) {
      return elevator.monitorStatus?.currentTemp || elevator.monitorStatus?.currentTemperature || '--';
    },

    // 获取最低温度
    getMinTemp(elevator) {
      return elevator.monitorStatus?.minTemp || elevator.monitorStatus?.minTemperature || '--';
    },

    // 获取最高温度
    getMaxTemp(elevator) {
      return elevator.monitorStatus?.maxTemp || elevator.monitorStatus?.maxTemperature || '--';
    },

    // 获取告警数量
    getAlarmCount(card) {
      return card.monitorStatus?.alarmCount || 0;
    },

    // 获取异常楼层
    getAbnormalFloors(elevator) {
      return elevator.monitorStatus?.abnormalFloors || [];
    },

    // 获取温度颜色
    getTempColor(temp) {
      if (temp === '--') return '#909399';
      const tempValue = parseFloat(temp);
      if (tempValue > 60) return '#f5222d'; // 红色-危险
      if (tempValue > 50) return '#faad14'; // 黄色-预警
      return '#52c41a'; // 绿色-正常
    },

    // 处理楼栋点击
    handleBuildingClick(building) {
      this.$emit('building-click', building);
    },

    // 处理单元点击
    handleUnitClick(unit) {
      this.$emit('unit-click', unit);
    },

    // 处理电梯点击
    handleElevatorClick(elevator) {
      this.$emit('elevator-click', elevator);
    },

    // 打开告警事件功能页面 - 封装在组件内部作为默认行为
    openAlarmEventsPage(elevator) {
      console.log('打开告警事件页面，电梯信息:', elevator);
      // 默认行为：直接跳转到告警事件页面
      this.$router.push({
        path: '/project/event',
        query: {
          lcCode: elevator.lcCode,
          source: 'monitor'
        }
      });

      // 同时触发事件，让父组件可以监听并执行额外逻辑
      this.$emit('alarm-events', elevator);
    },

    // 刷新数据
    refreshData() {
      this.loadMonitorData();
    }
  }
};
</script>

<style scoped>
/* 样式保持不变，与之前相同 */
.building-monitor {
  background-color: #f5f7fa;
}

.monitor-section {
  margin-bottom: 24px;
}

.section-title {
  margin: 12px 0;
  padding: 0 12px;
  border-left: 4px solid #1890ff;
  color: #303133;
  font-size: 14px;
  font-weight: 600;
}

/* 楼栋流式布局 */
.building-flow {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
}

.building-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  transition: all 0.3s ease;
}

.building-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  transform: translateY(-2px);
}

/* 楼栋头部 */
.building-header {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border-bottom: 1px solid #e8e8e8;
  cursor: pointer;
  transition: background-color 0.3s;
}

.building-header:hover {
  background: linear-gradient(135deg, #e6f7ff 0%, #bae7ff 100%);
}

.status-indicator {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-right: 8px;
  flex-shrink: 0;
}

.building-info {
  flex: 1;
  min-width: 0;
}

.building-name {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 2px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.building-code {
  font-size: 12px;
  color: #909399;
}

.building-status {
  font-size: 12px;
  font-weight: 500;
  margin-right: 8px;
}

.building-unit-count {
  font-size: 11px;
  color: #1890ff;
  background: #e6f7ff;
  padding: 2px 6px;
  border-radius: 10px;
  font-weight: 500;
}

/* 单元列表 */
.unit-list {
  padding: 4px;
}

.unit-item {
  margin-bottom: 8px;
  border: 1px solid #f0f0f0;
  border-radius: 6px;
  overflow: hidden;
}

.unit-header {
  display: flex;
  align-items: center;
  padding: 4px 12px 0 12px;
  background: #fafafa;
  cursor: pointer;
  transition: background-color 0.3s;
}

.unit-header:hover {
  background: #f0f0f0;
}

.unit-name {
  flex: 1;
  font-size: 12px;
  font-weight: 500;
  color: #303133;
  margin-left: 8px;
}

.unit-status {
  font-size: 11px;
  font-weight: 500;
  margin-right: 8px;
}

.unit-elevator-count {
  font-size: 10px;
  color: #52c41a;
  background: #f6ffed;
  padding: 2px 6px;
  border-radius: 10px;
}

/* 电梯列表 */
.elevator-list {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 8px;
  padding: 8px;
  background: #f8f9fa;
}

.elevator-item {
  background: white;
  border-radius: 4px;
  padding: 8px;
  cursor: pointer;
  transition: all 0.3s;
  border: 1px solid #e8e8e8;
  position: relative;
}

.elevator-item:hover {
  background: #e6f7ff;
  border-color: #1890ff;
}

.elevator-item.has-alarm {
  border-left: 3px solid #f5222d;
  background: #fff2f0;
}

.elevator-item.has-alarm:hover {
  background: #ffece8;
}

.elevator-content {
  display: flex;
  align-items: center;
  gap: 12px;
}

.elevator-basic {
  flex: 1;
  min-width: 0;
}

.elevator-name {
  font-size: 12px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.elevator-info {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

/* 告警徽章悬停效果 */
.alarm-badge-hoverable {
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
}

.alarm-badge-hoverable:hover {
  transform: scale(1.1);
  box-shadow: 0 2px 8px rgba(245, 34, 45, 0.4);
  z-index: 1;
}

.alarm-badge-hoverable:active {
  transform: scale(0.95);
}

/* 可点击的楼层区域 */
.clickable-floor-area {
  cursor: pointer;
  transition: all 0.3s ease;
  border-radius: 3px;
  padding: 2px 4px;
  margin: -2px -4px;
}

.clickable-floor-area:hover {
  background-color: rgba(245, 34, 45, 0.08);
  box-shadow: 0 1px 3px rgba(245, 34, 45, 0.2);
}

.clickable-floor-area:active {
  background-color: rgba(245, 34, 45, 0.12);
}

/* 单独为告警楼层区域添加悬停效果 */
.abnormal-floors.clickable-floor-area:hover .abnormal-label,
.abnormal-column.clickable-floor-area:hover .abnormal-label {
  font-weight: 600;
  text-decoration: underline;
}

.abnormal-floors.clickable-floor-area:hover .floor-list,
.abnormal-column.clickable-floor-area:hover .floor-list {
  font-weight: 600;
}

/* 楼层信息容器 */
.floor-info-container {
  margin-top: 4px;
  padding-top: 4px;
  border-top: 1px dashed #e8e8e8;
  font-size: 10px;
}

/* 单模式（只有一种楼层信息） */
.single-mode {
  display: flex;
  align-items: center;
  gap: 4px;
}

/* 双模式（同时显示两种楼层信息） */
.dual-floors {
  display: flex;
  gap: 8px;
}

.floor-column {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 4px;
  min-width: 0;
}

.abnormal-column {
  color: #f5222d;
}

.warning-column {
  color: #faad14;
}

/* 标签样式 */
.abnormal-label {
  color: #f5222d;
  font-weight: 500;
  flex-shrink: 0;
}

.warning-label {
  color: #faad14;
  font-weight: 500;
  flex-shrink: 0;
}

/* 楼层列表样式 */
.floor-list {
  font-weight: 500;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.abnormal-column .floor-list {
  color: #ff4d4f;
}

.warning-column .floor-list {
  color: #fa8c16;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 11px;
}

.info-item label {
  color: #909399;
  font-weight: 400;
}

.info-item span {
  color: #303133;
  font-weight: 500;
}

.elevator-temp {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 2px;
  min-width: 80px;
}

.current-temp {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 11px;
}

.current-temp label {
  color: #909399;
}

.temp-value {
  font-weight: 600;
  font-size: 12px;
}

.temp-range {
  display: flex;
  align-items: center;
  gap: 2px;
  font-size: 10px;
}

.min-temp {
  color: #1890ff;
}

.range-separator {
  color: #909399;
}

.max-temp {
  color: #f5222d;
}

.elevator-status {
  font-size: 10px;
  font-weight: 500;
  min-width: 30px;
  text-align: center;
}

/* 告警徽章 */
.alarm-badge {
  background: #f5222d;
  color: white;
  border-radius: 50%;
  width: 16px;
  height: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 10px;
  font-weight: bold;
  flex-shrink: 0;
}

/* 异常楼层信息 */
.abnormal-floors {
  margin-top: 4px;
  padding-top: 4px;
  border-top: 1px dashed #ffccc7;
  font-size: 10px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.abnormal-label {
  color: #f5222d;
  font-weight: 500;
}

.floor-list {
  color: #ff4d4f;
  font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .building-flow {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .building-flow {
    grid-template-columns: 1fr;
  }

  .elevator-list {
    grid-template-columns: 1fr;
  }

  .elevator-content {
    flex-direction: column;
    align-items: flex-start;
    gap: 6px;
  }

  .elevator-temp {
    align-items: flex-start;
  }

  .dual-floors {
    flex-direction: column;
    gap: 2px;
  }

  .floor-column {
    flex: none;
  }

  .alarm-badge-hoverable {
    min-width: 20px;
    min-height: 20px;
  }

  .clickable-floor-area {
    padding: 4px 6px;
    margin: -4px -6px;
  }
}

@media (max-width: 480px) {
  .elevator-list {
    grid-template-columns: 1fr;
    gap: 6px;
  }

  .building-flow {
    grid-template-columns: 1fr;
  }

  .monitor-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }

  .header-actions {
    width: 100%;
    display: flex;
    gap: 8px;
  }

  .header-actions .el-button {
    flex: 1;
  }
}

/* 加载状态 */
.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40px;
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 40px;
  color: #909399;
}

.empty-state .el-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

/* 单元状态指示器优化 */
.unit-header .status-indicator {
  width: 10px;
  height: 10px;
}
</style>
